import Vue from 'vue'

const baseUrl = 'http://localhost:8681/background';
// const baseUrl = 'http://www.uychen.com/json/background';


const http = {
  baseUrl,
  post(url, data, callbackSuccess, callbackError) {
    let params;
    if (data != null) {
      params = Vue.prototype.$qs.stringify(data);
    }
    Vue.prototype.axios.post(baseUrl + url, params)
      .then(res => {
        let root = res.data;
        if (root.code != 0) {
          callbackSuccess(root.data);
          return;
        } else {
          if (callbackError != null) {
            callbackError(root.msg);
          }
          return;
        }
      }).catch(error => {
      if (callbackError != null) {
        callbackError("请求服务器异常: " + error);
      }
      return;
    });
  },
  get(url, data, callbackSuccess, callbackError) {
    let params = '';
    if (data != null) {
      params = "?" + Vue.prototype.$qs.stringify(data);
    }
    Vue.prototype.axios({
      method: 'get',
      url: baseUrl + url + params,
    })
      .then(res => {
        let root = res.data;
        if (root.code != 0) {
          if (root.hasOwnProperty('data')) {
            callbackSuccess(root.data);
          } else {
            callbackSuccess();
          }
          return;
        } else {
          if (callbackError != null) {
            callbackError(root.msg);
          }
          return;
        }
      })
      .catch(error => {
        if (callbackError != null) {
          callbackError("请求服务器异常: " + error.status);
        }
        return;
      });
  },
  postJson(url, data, callbackSuccess, callbackError) {
    Vue.prototype.axios.post(baseUrl + url, JSON.stringify(data), {
      headers: {"Content-Type": "application/json"}
    })
      .then(res => {
        let root = res.data;
        if (root.code != 0) {
          callbackSuccess(root.data);
          return;
        } else {
          if (callbackError != null) {
            callbackError(root.msg);
          }
          return;
        }
      }).catch(error => {
      if (callbackError != null) {
        callbackError("请求服务器异常: " + error);
      }
      return;
    });
  }
};
export default http
